package com.cjlgb.design.upms.receiver;

import com.cjlgb.design.upms.api.entity.SysMenu;
import com.cjlgb.design.upms.api.entity.SysRoleMenu;
import com.cjlgb.design.upms.service.SysRoleMenuService;
import com.cjlgb.design.upms.channel.SysMenuChannel;
import com.cjlgb.design.upms.channel.SysRoleChannel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * @author WFT
 * @date 2019/8/29
 * description: 系统菜单异步接口消费逻辑
 */
@Slf4j
@Component
@RequiredArgsConstructor
@EnableBinding(value = SysMenuChannel.class)
public class SysMenuReceiver {

    private final SysRoleMenuService roleMenuService;
    private final SysRoleChannel roleChannel;

    /**
     * 监听新增菜单,将菜单授权于系统角色
     * @param menu 菜单
     */
    @StreamListener(value = SysMenuChannel.INPUT, condition = "headers['method']=='add'")
    public void listenerAdd(SysMenu menu){
        //  系统角色Id
        long roleId = 1;
        SysRoleMenu roleMenu = new SysRoleMenu(roleId,menu.getId(),menu.getType());
        this.roleMenuService.save(roleMenu);
        //  通知队列更新管理员账号缓存
        this.roleChannel.output().send(
                MessageBuilder.withPayload(roleId)
                        .setHeader("method", "authorize").build()
        );
    }

    /**
     * 监听菜单的权限标识被更改
     * @param menuId 菜单Id
     */
    @StreamListener(value = SysMenuChannel.INPUT, condition = "headers['method']=='edit'")
    public void listenerEdit(Long menuId){
        Collection<Long> roleIds = this.roleMenuService.selectRoleIdsByMenuId(menuId);
        roleIds.forEach(roleId -> {
            //  通知队列更新账号缓存
            this.roleChannel.output().send(
                    MessageBuilder.withPayload(roleId)
                            .setHeader("method", "authorize").build()
            );
        });
    }

    /**
     * 监听菜单被删除
     * @param menuId 菜单Id
     */
    @StreamListener(value = SysMenuChannel.INPUT, condition = "headers['method']=='delete'")
    public void listenerDelete(Long menuId){
        //  通知受关联角色更新缓存
        this.listenerEdit(menuId);
        //  删除菜单与角色间的关联
        this.roleMenuService.deleteByMenuId(menuId);
    }

}
